<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>调查数据统计</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", sans-serif;
            background: #f5f5f5;
            padding: 20px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 12px;
            margin-bottom: 30px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        }

        .header h1 {
            margin-bottom: 10px;
        }

        .stats-overview {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
        }

        .stat-card h3 {
            color: #666;
            font-size: 14px;
            margin-bottom: 10px;
        }

        .stat-card .number {
            font-size: 36px;
            font-weight: bold;
            color: #667eea;
        }

        .section {
            background: white;
            padding: 30px;
            border-radius: 12px;
            margin-bottom: 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .section h2 {
            color: #333;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #667eea;
        }

        .chart {
            margin-top: 20px;
        }

        .bar-chart-item {
            margin-bottom: 15px;
        }

        .bar-chart-label {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
            font-size: 14px;
        }

        .progress-bar {
            width: 100%;
            height: 24px;
            background: #e0e0e0;
            border-radius: 12px;
            overflow: hidden;
            position: relative;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 12px;
            font-weight: bold;
            transition: width 0.5s ease;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }

        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #e0e0e0;
        }

        th {
            background: #f8f9fa;
            color: #333;
            font-weight: 600;
        }

        tr:hover {
            background: #f8f9fa;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;
            margin-right: 10px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-danger {
            background: #f44336;
            color: white;
        }

        .btn:hover {
            opacity: 0.9;
            transform: translateY(-2px);
        }

        .response-list {
            max-height: 400px;
            overflow-y: auto;
        }

        .response-card {
            background: #f8f9fa;
            padding: 15px;
            margin-bottom: 10px;
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }

        .response-card h4 {
            color: #333;
            margin-bottom: 8px;
        }

        .response-card p {
            color: #666;
            font-size: 14px;
            margin-bottom: 5px;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }

        .loading {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1 id="surveyTitle">📊 调查数据统计</h1>
            <p id="surveyDescription">加载中...</p>
        </div>

        <div class="stats-overview">
            <div class="stat-card">
                <h3>提交人数</h3>
                <div class="number" id="totalCount">0</div>
            </div>
        </div>

        <div id="statistics">
            <div class="loading">
                <h2>加载中...</h2>
                <p>正在获取统计数据</p>
            </div>
        </div>

        <div class="section">
            <h2>数据管理</h2>
            <button class="btn btn-primary" onclick="exportToCSV()">导出为CSV</button>
            <button class="btn btn-primary" onclick="exportToJSON()">导出为JSON</button>
            <button class="btn btn-danger" onclick="clearData()">清空所有数据</button>
            <button class="btn btn-primary" onclick="location.href='/admin'">返回管理后台</button>
        </div>
    </div>

    <script>
        let surveyId = null;
        let surveyConfig = null;
        let surveyData = [];

        // 页面加载时执行
        window.onload = function() {
            // 从URL中提取surveyId
            const pathParts = window.location.pathname.split('/');
            surveyId = pathParts[pathParts.length - 1];

            if (!surveyId) {
                showError('无效的调查ID');
                return;
            }

            loadData();
        };

        // 加载数据
        function loadData() {
            // 同时加载配置和数据
            Promise.all([
                fetch(`/api/survey/${surveyId}/config`).then(r => r.json()),
                fetch(`/api/data/${surveyId}`).then(r => r.json())
            ])
            .then(([config, data]) => {
                surveyConfig = config;
                surveyData = data;

                // 更新标题
                document.getElementById('surveyTitle').textContent = config.title;
                document.getElementById('surveyDescription').textContent =
                    `提交时间: ${new Date().toLocaleString('zh-CN')} | 共 ${data.length} 份数据`;

                // 更新统计
                document.getElementById('totalCount').textContent = data.length;

                // 生成统计
                generateStatistics();
            })
            .catch(err => {
                showError('加载数据失败: ' + err.message);
            });
        }

        // 生成统计
        function generateStatistics() {
            if (surveyData.length === 0) {
                document.getElementById('statistics').innerHTML = `
                    <div class="empty-state">
                        <h3>暂无数据</h3>
                        <p>还没有学生提交调查表</p>
                    </div>
                `;
                return;
            }

            let html = '';

            // 遍历每个部分
            surveyConfig.sections.forEach((section, sIndex) => {
                html += `
                    <div class="section">
                        <h2>${section.title}</h2>
                `;

                // 遍历每个问题
                section.questions.forEach((question, qIndex) => {
                    html += generateQuestionStats(question);
                });

                html += '</div>';
            });

            document.getElementById('statistics').innerHTML = html;
        }

        // 生成单个问题的统计
        function generateQuestionStats(question) {
            // 跳过展示类型
            if (question.type === 'code_display' || question.type === 'text_display') {
                return '';
            }

            let html = `<h3 style="margin-top: 20px; color: #555;">${question.question}</h3>`;

            switch (question.type) {
                case 'text':
                case 'textarea':
                    html += generateTextStats(question);
                    break;

                case 'radio':
                    html += generateRadioStats(question);
                    break;

                case 'checkbox':
                    html += generateCheckboxStats(question);
                    break;

                case 'table':
                    html += generateTableStats(question);
                    break;

                default:
                    html += `<p style="color: #999;">未知题型: ${question.type}</p>`;
            }

            return html;
        }

        // 文本题统计
        function generateTextStats(question) {
            let html = '<div class="response-list">';

            surveyData.forEach((submission, index) => {
                const answer = submission.responses[question.id];
                if (answer && answer.trim()) {
                    html += `
                        <div class="response-card">
                            <h4>${submission.name || '匿名'}</h4>
                            <p>${escapeHtml(answer)}</p>
                        </div>
                    `;
                }
            });

            if (html === '<div class="response-list">') {
                html += '<p style="color: #999; padding: 20px;">暂无回答</p>';
            }

            html += '</div>';
            return html;
        }

        // 单选题统计
        function generateRadioStats(question) {
            const counts = {};

            // 统计每个选项的数量
            surveyData.forEach(submission => {
                const answer = submission.responses[question.id];
                if (answer) {
                    counts[answer] = (counts[answer] || 0) + 1;
                }
            });

            return generateBarChart(counts, surveyData.length);
        }

        // 多选题统计
        function generateCheckboxStats(question) {
            const counts = {};

            // 统计每个选项的数量
            surveyData.forEach(submission => {
                const answers = submission.responses[question.id];
                if (Array.isArray(answers)) {
                    answers.forEach(answer => {
                        counts[answer] = (counts[answer] || 0) + 1;
                    });
                }
            });

            // 按数量排序,取Top10
            const sorted = Object.entries(counts)
                .sort((a, b) => b[1] - a[1])
                .slice(0, 10);

            const sortedCounts = {};
            sorted.forEach(([key, value]) => {
                sortedCounts[key] = value;
            });

            return generateBarChart(sortedCounts, surveyData.length);
        }

        // 表格题统计
        function generateTableStats(question) {
            let html = '<table><thead><tr><th>选项</th>';

            // 表头
            question.columns.forEach(col => {
                html += `<th>${escapeHtml(col)}</th>`;
            });
            html += '</tr></thead><tbody>';

            // 每一行
            question.rows.forEach(row => {
                html += `<tr><td><strong>${escapeHtml(row)}</strong></td>`;

                const counts = {};
                question.columns.forEach(col => {
                    counts[col] = 0;
                });

                // 统计这一行每列的数量
                surveyData.forEach(submission => {
                    const tableData = submission.responses[question.id];
                    if (tableData && typeof tableData === 'object') {
                        const answer = tableData[row];
                        if (answer && counts[answer] !== undefined) {
                            counts[answer]++;
                        }
                    }
                });

                question.columns.forEach(col => {
                    html += `<td>${counts[col]}</td>`;
                });

                html += '</tr>';
            });

            html += '</tbody></table>';
            return html;
        }

        // 生成柱状图
        function generateBarChart(counts, total) {
            if (Object.keys(counts).length === 0) {
                return '<p style="color: #999; padding: 20px;">暂无数据</p>';
            }

            let html = '<div class="chart">';

            for (let [label, count] of Object.entries(counts)) {
                const percent = total > 0 ? (count / total * 100).toFixed(1) : 0;
                html += `
                    <div class="bar-chart-item">
                        <div class="bar-chart-label">
                            <span>${escapeHtml(label)}</span>
                            <span>${count}人 (${percent}%)</span>
                        </div>
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: ${percent}%">
                                ${percent}%
                            </div>
                        </div>
                    </div>
                `;
            }

            html += '</div>';
            return html;
        }

        // 导出为CSV
        function exportToCSV() {
            if (surveyData.length === 0) {
                alert('暂无数据可导出');
                return;
            }

            // CSV表头
            let csv = '姓名,提交时间';

            // 收集所有问题ID
            const questionIds = [];
            surveyConfig.sections.forEach(section => {
                section.questions.forEach(q => {
                    if (q.type !== 'code_display' && q.type !== 'text_display') {
                        questionIds.push({
                            id: q.id,
                            question: q.question,
                            type: q.type
                        });
                        csv += `,"${q.question.replace(/"/g, '""')}"`;
                    }
                });
            });

            csv += '\n';

            // 数据行
            surveyData.forEach(submission => {
                csv += `"${(submission.name || '匿名').replace(/"/g, '""')}",`;
                csv += `"${new Date(submission.timestamp).toLocaleString('zh-CN')}"`;

                questionIds.forEach(q => {
                    const answer = submission.responses[q.id];

                    if (q.type === 'checkbox') {
                        csv += `,"${Array.isArray(answer) ? answer.join('; ') : ''}"`;
                    } else if (q.type === 'table') {
                        const values = [];
                        if (answer && typeof answer === 'object') {
                            for (let [key, val] of Object.entries(answer)) {
                                values.push(`${key}:${val}`);
                            }
                        }
                        csv += `,"${values.join('; ')}"`;
                    } else {
                        csv += `,"${(answer || '').toString().replace(/"/g, '""')}"`;
                    }
                });

                csv += '\n';
            });

            downloadFile('调查数据.csv', '\ufeff' + csv); // UTF-8 BOM
        }

        // 导出为JSON
        function exportToJSON() {
            if (surveyData.length === 0) {
                alert('暂无数据可导出');
                return;
            }

            downloadFile('调查数据.json', JSON.stringify(surveyData, null, 2));
        }

        // 下载文件
        function downloadFile(filename, content) {
            const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            a.click();
            URL.revokeObjectURL(url);
        }

        // 清空数据
        function clearData() {
            if (!confirm('确定要清空所有调查数据吗?\n此操作不可恢复!')) {
                return;
            }

            fetch(`/api/clear/${surveyId}`, { method: 'POST' })
                .then(r => r.json())
                .then(result => {
                    if (result.success) {
                        alert('✅ 数据已清空');
                        location.reload();
                    } else {
                        alert('❌ 清空失败: ' + result.message);
                    }
                })
                .catch(err => {
                    alert('❌ 清空失败: ' + err.message);
                });
        }

        function showError(message) {
            document.getElementById('statistics').innerHTML = `
                <div class="empty-state">
                    <h3>出错了</h3>
                    <p>${message}</p>
                </div>
            `;
        }

        function escapeHtml(unsafe) {
            if (!unsafe) return '';
            return unsafe.toString()
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // 自动刷新(每30秒)
        setInterval(() => {
            loadData();
        }, 30000);
    </script>
</body>
</html>
